package com.itlong.cloud.iot.service.server.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.iot.model.v20170420.*;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.common.DeviceOnlineVO;
import com.itlong.cloud.POJO.VO.common.IotInfoVO;
import com.itlong.cloud.POJO.VO.common.ProjectIotInfo;
import com.itlong.cloud.POJO.VO.property.CloudControllerVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.commons.dao.*;
import com.itlong.cloud.commons.service.IDeviceCloudControllerInfoService;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.iot.alibaba.util.AliRequestClient;
import com.itlong.cloud.iot.dao.IotInteriorDao;
import com.itlong.cloud.iot.huawei.util.HuawTokenClient;
import com.itlong.cloud.iot.service.server.AliIotServerService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.network.https.HttpsPost;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <desc>
 *      iot公共基础服务接口阿里实现类
 * </desc>
 *
 * @createDate 2018-03-14
 */
@Service
@RefreshScope
public class AliIotServerServiceImpl extends AliRequestClient implements AliIotServerService{
    private static final Logger LOG = LoggerFactory.getLogger(AliIotServerServiceImpl.class);
    @Autowired
    IProductTypeInfoDao iProductTypeInfoDao;
    @Autowired
    IDeviceElevatorInfoDao iDeviceElevatorInfoDao;
    @Autowired
    RedisService redisService;
    @Autowired
    IDeviceEntranceInfoDao iDeviceEntranceInfoDao;
    @Autowired
    ICommonsDao iCommonsDao;
    @Autowired
    IDeviceCloudControllerInfoService iDeviceCloudControllerInfoService;
    @Autowired
    IotInteriorDao iotInteriorDao;
    @Autowired
    IJDServiceDao ijdServiceDao;
    @Autowired
    HuawTokenClient huawTokenClient;
    @Value("${" + PlatformConstants.HUAWEI_PROJECT_ID + "}")
    private String projectId;
//    @Value("${" + PlatformConstants.JD_PROJECT_ID + "}")
//    private String jdProjectId;
    @Value("${" + PlatformConstants.JD_URL + "}")
    private String jdUrl;
    @Value("${" + PlatformConstants.JD_APPID + "}")
    private String appid;
    @Value("${" + PlatformConstants.JD_SECRET + "}")
    private String appsecret;

    /**
     * <desc>
     *     创建产品
     * </desc>
     *
     * @param productTypePO
     * @return
     * @author Jiaqi.X
     * @createDate 2018/03/17
     */
    public boolean createProduct(ProductTypePO productTypePO) throws Exception{
        try {
            String iotProductKey = "";
            CreateProductRequest request = new CreateProductRequest();
            request.setName(productTypePO.getTypeName());
            request.setDesc(productTypePO.getRemark());
            CreateProductResponse response = (CreateProductResponse)executeTest(request);
            if (response == null){
                LOG.info("创建产品失败！无法获取CreateProductResponse对象");
                return false;
            }
            if (response != null && response.getSuccess() != false) {
                LOG.info("创建产品成功！productKey:" + response.getProductInfo().getProductKey());
                iotProductKey = response.getProductInfo().getProductKey();
                ProductTypePO productTypeVO = new ProductTypePO();
                productTypeVO.setTypePid(productTypePO.getTypePid());
                productTypeVO.setIotProductKey(iotProductKey);
                //根据产品型号ID更新iot的产品KEY
                iProductTypeInfoDao.updateByNotNull(productTypeVO);
                return true;
            } else {
                LOG.info("创建产品失败！requestId:" + response.getRequestId() + "原因:" + response.getErrorMessage());
                return false;
            }
        }catch (Exception e){
            LOG.error("创建产品失败！e:" +  e.getMessage());
            return  false;
        }

    }

    /**
     * <desc>
     *     修改产品
     * </desc>
     *
     * @param productTypePO
     * @return
     * @author Jiaqi.X
     * @createDate 2018/03/17
     */
    public boolean updateProduct(ProductTypePO productTypePO) throws Exception{
        try {
            UpdateProductRequest request = new UpdateProductRequest();
            request.setProductKey(productTypePO.getIotProductKey());
            request.setProductName(productTypePO.getTypeName());
            request.setProductDesc(productTypePO.getRemark());
            UpdateProductResponse response = (UpdateProductResponse)executeTest(request);
            if (response == null){
                LOG.info("创建产品失败！无法获取CreateProductResponse对象");
                return false;
            }
            if (response != null && response.getSuccess() != false) {
                LOG.info("修改产品成功！");
                return  true;
            } else {
                LOG.info("修改产品失败！requestId:" + response.getRequestId() + "原因:" + response.getErrorMessage());
                return  false;
            }
        }catch (Exception e){
            LOG.error("修改产品失败！e:" +  e.getMessage());
            return  false;
        }
    }

    /**
     * <desc>
     *     注册设备
     * </desc>
     *
     * @param iotInfoVO
     * @return
     * @throws Exception
     * @author Jiaqi.X
     * @createDate 2018/03/17
     */
    @Override
    public boolean registDevice(IotInfoVO iotInfoVO) throws  Exception{
        try {
            RegistDeviceRequest request = new RegistDeviceRequest();
            request.setProductKey(iotInfoVO.getIotProductKey());
            String[] deviceUniques = StringHandlerUtil.splitString(iotInfoVO.getDeviceUnique());
            Integer deviceType = 0;
            //一卡通使用项目编号作为iot设备编号,每个项目只创建一个一卡通iot设备
            if (deviceUniques[0] != null && deviceUniques[0].length() == 8) {
                deviceType = 9;
            }else {
                deviceType = StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUniques[0]);
            }
            request.setDeviceName(deviceUniques[0]);
            RegistDeviceResponse response = (RegistDeviceResponse)executeTest(request);
            LOG.info("创建设备成功！deviceName:" + response.getDeviceName() + ",deviceSecret:" + response.getDeviceSecret());
            if (response.getDeviceSecret() == null) {//注册不上的时候走一次查询
                QueryDeviceByNameResponse query = null;
                if (StringUtils.isBlank(response.getDeviceName())) {
                    //如果创建失败，查询设备信息
                    QueryDeviceByNameRequest queryRequest = new QueryDeviceByNameRequest();
                    queryRequest.setDeviceName(deviceUniques[0]);
                    queryRequest.setProductKey(iotInfoVO.getIotProductKey());
                    query = (QueryDeviceByNameResponse) executeTest(queryRequest);
                }
                if (query == null) {
                    LOG.info("查询产品失败！无法获取CreateProductResponse对象");
                }else {
                    response.setDeviceSecret(query.getDeviceInfo().getDeviceSecret());
                    response.setDeviceId(query.getDeviceInfo().getDeviceId());
                    response.setDeviceStatus(query.getDeviceInfo().getDeviceStatus());
                    response.setDeviceName(query.getDeviceInfo().getDeviceName());
                }
            }
            String iotDeviceId = response.getDeviceId();
            String iotDeviceSecret = response.getDeviceSecret();
            String iotDeviceStatus = response.getDeviceStatus();
            if (deviceType == 1) {
                DeviceElevatorInfoPO deviceElevatorInfoPO = new DeviceElevatorInfoPO(iotInfoVO.getDeviceUnique());
                deviceElevatorInfoPO.setIotDeviceId(iotDeviceId);
                deviceElevatorInfoPO.setIotDeviceSecret(iotDeviceSecret);
                deviceElevatorInfoPO.setIotDeviceStatus(iotDeviceStatus);
                //根据云电梯设备唯一码更新iot的云电梯配置信息
                iDeviceElevatorInfoDao.updateByNotNull(deviceElevatorInfoPO);
            } else if (deviceType == 2) {
                for (int i = 0; i < deviceUniques.length; i++) {
                    DeviceEntranceInfoPO deviceEntranceInfoPO = new DeviceEntranceInfoPO(deviceUniques[i]);
                    deviceEntranceInfoPO.setIotDeviceName(response.getDeviceName());
                    deviceEntranceInfoPO.setIotDeviceId(iotDeviceId);
                    deviceEntranceInfoPO.setIotDeviceSecret(iotDeviceSecret);
                    deviceEntranceInfoPO.setIotDeviceStatus(iotDeviceStatus);
                    iDeviceEntranceInfoDao.updateIotInfo(deviceEntranceInfoPO);
                }
            } else if (deviceType == 5) {
                DeviceCloudControllerInfoPO deviceCloudControllerInfoPO = new DeviceCloudControllerInfoPO();
                deviceCloudControllerInfoPO.setDeviceUnique(iotInfoVO.getDeviceUnique());
                deviceCloudControllerInfoPO.setIotDeviceId(iotDeviceId);
                deviceCloudControllerInfoPO.setIotDeviceSecret(iotDeviceSecret);
                deviceCloudControllerInfoPO.setIotDeviceStatus(iotDeviceStatus);
                iDeviceCloudControllerInfoService.updateIotInfoByDeviceUnique(deviceCloudControllerInfoPO);
            } else if (deviceType == 4) {//平板
                DevicePadInfoPO devicePadInfoPO = new DevicePadInfoPO();
                devicePadInfoPO.setDeviceUnique(iotInfoVO.getDeviceUnique());
                devicePadInfoPO.setIotDeviceId(iotDeviceId);
                devicePadInfoPO.setIotDeviceSecret(iotDeviceSecret);
                devicePadInfoPO.setIotDeviceStatus(iotDeviceStatus);
                iCommonsDao.updatePadIotInfoByDeviceUnique(devicePadInfoPO);
            } else if (deviceType == 3) {//云对讲
                DeviceCloudIntercomInfoPO deviceCloudIntercomInfoPO = new DeviceCloudIntercomInfoPO();
                deviceCloudIntercomInfoPO.setDeviceUnique(iotInfoVO.getDeviceUnique());
                deviceCloudIntercomInfoPO.setIotDeviceId(iotDeviceId);
                deviceCloudIntercomInfoPO.setIotDeviceSecret(iotDeviceSecret);
                deviceCloudIntercomInfoPO.setIotDeviceStatus(iotDeviceStatus);
                iCommonsDao.updateTalkIotInfoByDeviceUnique(deviceCloudIntercomInfoPO);
            } else if (deviceType == 9) {//一卡通
                iCommonsDao.updateSmartCardIotInfo(iotInfoVO.getDeviceUnique(),iotDeviceId,iotDeviceSecret);
            } else {
                LOG.info("创建设备失败！requestId:" + response.getRequestId() + "原因：" + response.getErrorMessage());
                return false;
            }
            return true;
        }catch (Exception e){
            LOG.error("创建设备失败！e:" +  e.getMessage());
            return  false;
        }
    }

    public static void main(String[] args) {
        for(int i=0;i<4;i++) {
            System.out.println(LogicIdUtil.bussinessId());
        }
    }

    /**
     * <desc>
     *     保存设备属性
     * </desc>
     *
     * @param productKey
     * @param deviceUnique
     * @param deviceProJs  JSONObject对象
     * @return
     * @author Jiaqi.X
     * @createDate 2018/03/17
     */
    public boolean saveDeviceProp(String productKey,String deviceUnique,JSONObject deviceProJs) throws Exception{
        try {
            SaveDevicePropRequest request = new SaveDevicePropRequest();
            request.setProductKey(productKey);
            request.setDeviceName(deviceUnique);
            request.setProps(JSON.toJSONString(deviceProJs));
            SaveDevicePropResponse response = (SaveDevicePropResponse) executeTest(request);
            if (response == null){
                LOG.info("创建产品失败！无法获取CreateProductResponse对象");
                return false;
            }
            if (response != null && response.getSuccess() != false) {
                LOG.info("保存设备属性成功！");
                return true;
            } else {
                LOG.info("保存设备属性失败！requestId:" + response.getRequestId() + "原因：" + response.getErrorMessage());
                return  false;
            }
        }catch (Exception e){
            LOG.info("保存设备属性失败！e:" +  e.getMessage());
            return  false;
        }
    }

    /**
     * <desc>
     *     批量获取同一个产品型号下的设备工作状态
     * </desc>
     *
     * @param productKey
     * @param deviceUniques 设备序列号 多个,号分隔
     * @return
     * @author Jiaqi.X
     * @createDate  2018/03/17
     */
    @Override
    public String batchGetDeviceState(String productKey,String deviceUniques){
        List<String> deviceNames = new ArrayList<>();
        String[] deviceArray = StringHandlerUtil.splitString(deviceUniques);

        //判断是否是华为设备
        String deviceUnique = deviceArray[0];
        if(StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 1 || StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique)==5
                || StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique)==2) {
            ProjectIotInfo projectIotInfo = iotInteriorDao.getProjectIotInfoByProjectId(StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique),
                    StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique), deviceUnique);
            if (projectIotInfo.getIotFlag() != 1 && StringUtils.isNotBlank(projectIotInfo.getHuaweiIotId()) &&
                    (StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 1 ||
                            StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 5 ||
                            StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 2)) {
                try {
                    String result = HttpsPost.doGet(huawTokenClient.getAccessToken(), "https://iotdm.cn-north-4.myhuaweicloud.com/v5/iot/" + projectId + "/devices/" + projectIotInfo.getHuaweiIotId(), null);
                    Map<String, Object> resultMap = JsonUtil.toObject(result, HashMap.class);
                    if(resultMap.get("error_code") != null){
                        redisService.del(RedisConstant.HUAWEI_ACCESS_TOKEN_REDIS_KEY);
                        result = HttpsPost.doGet(huawTokenClient.getAccessToken(), "https://iotdm.cn-north-4.myhuaweicloud.com/v5/iot/" + projectId + "/devices/" + projectIotInfo.getHuaweiIotId(), null);
                        resultMap = JsonUtil.toObject(result, HashMap.class);
                    }
                    LOG.info("【查询华为云iot设备信息返回结果】"+JsonUtil.toJSON(resultMap));
                    String online = "OFFLINE";
                    if (resultMap.containsKey("status")) {
                        online = resultMap.get("status").toString();
                    }
                    DeviceOnlineVO vo = new DeviceOnlineVO(deviceUnique, DateUtil.addCurrentTime(new Date(), 120000), online);
                    //设置设备的在线离线状态
                    LOG.info("=====批量获取同一个产品型号下的设备工作状态======>{}",vo);
                    redisService.set(RedisConstant.REDIS_IOT_CLOUD_DEVICE_ONLINE_STATE_CACHE + deviceUnique,
                            RedisConstant.REDIS_IOT_CLOUD_DEVICE_ONLINE_STATE_CACHE_TIME, vo);
                    try {
                        //处理列表中可能离线的设备状态
                        if ("ONLINE".equals(vo.getStatus())) {
                            if (StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 1) {
                                redisService.set(RedisConstant.DEVICE_ELEVATOR_IS_ONLINE_KEY + deviceUnique, "1");
                            } else if (StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 2) {
                                List<DeviceEntranceInfoPO> list = iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceUnique);
                                if (list.size() == 0) {
                                    list = iDeviceEntranceInfoDao.getDoorByGroup(deviceUnique);
                                }
                                for (DeviceEntranceInfoPO po : list) {
                                    if (po.getEntranceCategory() == 22 || po.getEntranceCategory() == 25) {//门禁
                                        redisService.set(RedisConstant.DEVICE_ENTRANCE_IS_ONLINE_KEY + po.getDeviceUnique(), "1");
                                    } else if (po.getEntranceCategory() == 23) {//联动器
                                        redisService.set(RedisConstant.DEVICE_WIPPEN_IS_ONLINE_KEY + po.getDeviceUnique(), "1");
                                    }
                                }
                            } else if (StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 5) {
                                redisService.set(RedisConstant.DEVICE_CLUSTER_IS_ONLINE_KEY + deviceUnique, "1");
                            }
                        }else{
                            if (StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 1) {
                                redisService.set(RedisConstant.DEVICE_ELEVATOR_IS_ONLINE_KEY + deviceUnique, "0");
                            } else if (StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 2) {
                                List<DeviceEntranceInfoPO> list = iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceUnique);
                                if (list.size() == 0) {
                                    list = iDeviceEntranceInfoDao.getDoorByGroup(deviceUnique);
                                }
                                for (DeviceEntranceInfoPO po : list) {
                                    if (po.getEntranceCategory() == 22 || po.getEntranceCategory() == 25) {//门禁
                                        redisService.set(RedisConstant.DEVICE_ENTRANCE_IS_ONLINE_KEY + po.getDeviceUnique(), "0");
                                    } else if (po.getEntranceCategory() == 23) {//联动器
                                        redisService.set(RedisConstant.DEVICE_WIPPEN_IS_ONLINE_KEY + po.getDeviceUnique(), "0");
                                    }
                                }
                            } else if (StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUnique) == 5) {
                                redisService.set(RedisConstant.DEVICE_CLUSTER_IS_ONLINE_KEY + deviceUnique, "0");
                            }
                        }
                    }catch (Exception e){

                    }
                    return online;
                } catch (Exception e) {
                    LOG.error(String.format("【查询华为云设备信息失败】deviceUnique%s",deviceUnique),e);
                }
            }
        }

        for (int i=0;i<deviceArray.length;i++){
            deviceNames.add(deviceArray[i]);
        }

        BatchGetDeviceStateRequest request = new BatchGetDeviceStateRequest();
        request.setProductKey(productKey);
        request.setDeviceNames(deviceNames);
        BatchGetDeviceStateResponse response = (BatchGetDeviceStateResponse)executeTest(request);
        if (response == null){
            LOG.info("创建产品失败！无法获取CreateProductResponse对象");
            return null;
        }
        if (response != null && response.getSuccess() != false) {
           LOG.info("查询设备成功！ " + JSONObject.toJSONString(response));
            List<BatchGetDeviceStateResponse.DeviceStatus> deviceStatusList = response.getDeviceStatusList();
            if (deviceStatusList != null&&deviceStatusList.size()>0){
                for (BatchGetDeviceStateResponse.DeviceStatus deviceStatus:deviceStatusList){
                    DeviceOnlineVO vo = new DeviceOnlineVO(deviceStatus.getDeviceName(), DateUtil.addCurrentTime(new Date(), 120000),deviceStatus.getStatus());
                    //设置设备的在线离线状态
                    redisService.set(RedisConstant.REDIS_IOT_CLOUD_DEVICE_ONLINE_STATE_CACHE + deviceStatus.getDeviceName(),
                            RedisConstant.REDIS_IOT_CLOUD_DEVICE_ONLINE_STATE_CACHE_TIME, vo);
                }
            }
            return deviceStatusList.get(0).getStatus();
        } else {
            LOG.info("查询设备失败！requestId:" + response.getRequestId() + "原因：" + response.getErrorMessage());
            return  null;
        }
    }

    /**
     * <desc>
     *     批量获取同一个产品型号下的设备工作状态并保存到缓存中
     * </desc>
     *
     * @param productKey
     * @param deviceUniques 设备序列号 多个,号分隔
     * @param type 设备型号:1云对讲,2云电梯,3云门禁,4群控器,5联动器,6平板,7一卡通,8一体式人脸识别门禁
     * @return
     * @author Qiang.S
     * @createDate  2019/07/04
     */
    @Override
    public void batchGetDeviceStateForOnline(String productKey, List<CloudControllerVO> deviceUniques, String type){
        List<String> deviceNames = new ArrayList<>();
        for (CloudControllerVO vo : deviceUniques){
            deviceNames.add(vo.getDeviceUnique());
        }
        //每次最多50个设备查询
        boolean flag = true;
        int size = deviceNames.size();
        List<String> deviceNamesOther;
        while (flag) {
            if (size > 50) {
                deviceNamesOther = deviceNames.subList(size-50,size);
                size = size-50;
            }else {
                deviceNamesOther = deviceNames.subList(0,size);
                flag = false;
            }
            BatchGetDeviceStateRequest request = new BatchGetDeviceStateRequest();
            request.setProductKey(productKey);
            request.setDeviceNames(deviceNamesOther);
            BatchGetDeviceStateResponse response = (BatchGetDeviceStateResponse)executeTest(request);
            if (response == null){
                LOG.info("查询产品失败！无法获取CreateProductResponse对象");
            }
            if (response != null && response.getSuccess() != false) {
                List<BatchGetDeviceStateResponse.DeviceStatus> deviceStatusList = response.getDeviceStatusList();
                if (deviceStatusList != null&&deviceStatusList.size()>0){
                    for (BatchGetDeviceStateResponse.DeviceStatus deviceStatus:deviceStatusList){
                        //headerOffline(type, deviceStatus);
                        if ("1".equals(type) && "ONLINE".equals(deviceStatus.getStatus())) {//云对讲
                            redisService.set(RedisConstant.DEVICE_INTERCOM_IS_ONLINE_KEY+deviceStatus.getDeviceName(),RedisConstant.DEVICE_INTERCOM_IS_ONLINE_CACHE_TIME,"2");
                        }
                        if(("2".equals(type) || "4".equals(type)) && StringHandlerUtil.getProjectIdByDeviceUnique(deviceStatus.getDeviceName()).equals(redisService.get(PlatformConstants.JD_PROJECT_ID))){
                            //推送京东设备状态
                            Map<String,Object> params = new HashMap<>();
                            params.put("id",LogicIdUtil.bussinessId());
                            Map<String,Object> protocol = new HashMap<>();
                            protocol.put("version","1.0");
                            protocol.put("name","JD-IOT-ESTATE-DEVICE");
                            Map<String,Object> client = new HashMap<>();
                            client.put("appid",appid);
                            Map<String,Object> param = new HashMap<>();
                            String jdDeviceId = ijdServiceDao.getJdDeviceId(deviceStatus.getDeviceName(),StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceStatus.getDeviceName()));
                            if(StringUtils.isNotBlank(jdDeviceId)){
                                param.put("deviceId",jdDeviceId);
                                param.put("status",deviceStatus.getStatus().equals("ONLINE") ? "1":"0");
                                params.put("protocol",protocol);
                                params.put("client",client);
                                params.put("params",param);
                                try {
                                    params = DesEncryptUtil.getJdSign(JsonUtil.toJSON(params),PlatformConstants.JD_CHANGEONLINESTATUS_URL,appsecret);
                                    HttpsPost.doJdPost(jdUrl+PlatformConstants.JD_CHANGEONLINESTATUS_URL,JsonUtil.toJSON(params));
                                }catch (Exception e){
                                    LOG.error("【iot定时任务设备在线状态获取京东加密参数失败】",e);
                                }
                            }
                        }
                        if ("2".equals(type) && "ONLINE".equals(deviceStatus.getStatus())) {//云电梯
                            redisService.set(RedisConstant.DEVICE_ELEVATOR_IS_ONLINE_KEY+deviceStatus.getDeviceName(),RedisConstant.DEVICE_ELEVATOR_IS_ONLINE_CACHE_TIME,"1");
                        }
                        if ("3".equals(type) && "ONLINE".equals(deviceStatus.getStatus())) {//云门禁
                            List<DeviceEntranceInfoPO> list = iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceStatus.getDeviceName());
                            if (list.size() == 0) {
                                list = iDeviceEntranceInfoDao.getDoorByGroup(deviceStatus.getDeviceName());
                            }
                            for (DeviceEntranceInfoPO po : list) {
                                redisService.set(RedisConstant.DEVICE_ENTRANCE_IS_ONLINE_KEY+po.getDeviceUnique(),RedisConstant.DEVICE_ENTRANCE_IS_ONLINE_CACHE_TIME,"1");
                            }
                        }
                        if ("4".equals(type) && "ONLINE".equals(deviceStatus.getStatus())) {//群控器
                            redisService.set(RedisConstant.DEVICE_CLUSTER_IS_ONLINE_KEY+deviceStatus.getDeviceName(),RedisConstant.DEVICE_CLUSTER_IS_ONLINE_CACHE_TIME,"1");
                        }
                        if ("5".equals(type) && "ONLINE".equals(deviceStatus.getStatus())) {//联动器
                            List<DeviceEntranceInfoPO> list = iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceStatus.getDeviceName());
                            if (list.size() == 0) {
                                list = iDeviceEntranceInfoDao.getDoorByGroup(deviceStatus.getDeviceName());
                            }
                            for (DeviceEntranceInfoPO po : list) {
                                redisService.set(RedisConstant.DEVICE_WIPPEN_IS_ONLINE_KEY+po.getDeviceUnique(),RedisConstant.DEVICE_WIPPEN_IS_ONLINE_CACHE_TIME,"1");
                            }
                        }
                        if ("6".equals(type) && "ONLINE".equals(deviceStatus.getStatus())) {//平板
                            redisService.set(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY+deviceStatus.getDeviceName(),RedisConstant.DEVICE_PAD_IS_ONLINE_CACHE_TIME,"2");
                        }
                        if ("7".equals(type) && "ONLINE".equals(deviceStatus.getStatus())) {//一卡通
                            redisService.set(RedisConstant.DEVICE_SMART_CARD_IS_ONLINE_KEY+deviceStatus.getDeviceName(),RedisConstant.DEVICE_SMART_CARD_IS_ONLINE_CACHE_TIME,"2");
                        }
                        if ("8".equals(type) && "ONLINE".equals(deviceStatus.getStatus())) {//一体式人脸识别门禁
                            List<DeviceEntranceInfoPO> list = iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceStatus.getDeviceName());
                            if (list.size() == 0) {
                                list = iDeviceEntranceInfoDao.getDoorByGroup(deviceStatus.getDeviceName());
                            }
                            for (DeviceEntranceInfoPO po : list) {
                                redisService.set(RedisConstant.DEVICE_UNIBODY_FACE_IS_ONLINE_KEY+po.getDeviceUnique(),RedisConstant.DEVICE_UNIBODY_FACE_IS_ONLINE_CACHE_TIME,"1");
                            }
                        }

                    }
                }
            } else {
//                LOG.info("查询设备失败！requestId:" + response.getRequestId() + "原因：" + response.getErrorMessage());
            }
        }
    }

    /**
     * <desc>
     *      保存设备在线日志
     * </desc>
     *
     * @param
     * @param type
     * @param deviceStatus
     * @return
     * @author caoshuai
     * @createDate 2020/11/24 18:16
     */
    private void  headerOffline(String type, BatchGetDeviceStateResponse.DeviceStatus deviceStatus) {
        String oldStatus = iotInteriorDao.getNewTimeDeviceStatus(deviceStatus.getDeviceName());
        if("0".equals(oldStatus)) {
            oldStatus = "OFFLINE";
        }else {
            oldStatus = "ONLINE";
        }
        Date nowTime = new Date();
        String IOTStatus = null;
        if("ONLINE".equals(deviceStatus.getStatus())) {
            IOTStatus = "ONLINE";
        }else {
            IOTStatus = "OFFLINE";
        }
//        if(IOTStatus.equals(oldStatus)){
//            return;
//        }
        if ("1".equals(type)) {//云对讲
//            String status = redisService.get(RedisConstant.DEVICE_INTERCOM_IS_ONLINE_KEY+deviceStatus.getDeviceName());
//            if(null == status || "0".equals(status)) {
//                status = "OFFLINE";
//            }else {
//                status = "ONLINE";
//            }
            if(!oldStatus.equals(IOTStatus)) {
                //保存上下线日志
                DeviceOnlineStatusAlterLogPO deviceOnlineStatusAlterLogPO = new DeviceOnlineStatusAlterLogPO();
                if("ONLINE".equals(IOTStatus)){
                    deviceOnlineStatusAlterLogPO.setOnlineStatus(1);
                }else {
                    deviceOnlineStatusAlterLogPO.setOnlineStatus(0);
                }
                deviceOnlineStatusAlterLogPO.setDeviceType(1);
                deviceOnlineStatusAlterLogPO.setDeviceUnique(deviceStatus.getDeviceName());
                deviceOnlineStatusAlterLogPO.setCreateTime(nowTime);
                deviceOnlineStatusAlterLogPO.setStatusAlterTime(nowTime);
                deviceOnlineStatusAlterLogPO.setStatus(1);
                saveOnlineStatusAlterLog(deviceOnlineStatusAlterLogPO);

            }
        }
        if ("2".equals(type)) {//云电梯
//            String status = redisService.get(RedisConstant.DEVICE_ELEVATOR_IS_ONLINE_KEY + deviceStatus.getDeviceName());
//            if(null == status || "0".equals(status)) {
//                status = "OFFLINE";
//            }else {
//                status = "ONLINE";
//            }

            if(!oldStatus.equals(IOTStatus)) {
                //保存上下线日志
                DeviceOnlineStatusAlterLogPO deviceOnlineStatusAlterLogPO = new DeviceOnlineStatusAlterLogPO();
                if("ONLINE".equals(IOTStatus)){
                    deviceOnlineStatusAlterLogPO.setOnlineStatus(1);
                }else {
                    deviceOnlineStatusAlterLogPO.setOnlineStatus(0);
                }
                deviceOnlineStatusAlterLogPO.setDeviceType(0);
                deviceOnlineStatusAlterLogPO.setDeviceUnique(deviceStatus.getDeviceName());
                deviceOnlineStatusAlterLogPO.setCreateTime(nowTime);
                deviceOnlineStatusAlterLogPO.setStatusAlterTime(nowTime);
                deviceOnlineStatusAlterLogPO.setStatus(1);
                saveOnlineStatusAlterLog(deviceOnlineStatusAlterLogPO);

            }
        }
        if ("3".equals(type)) {//云门禁
            List<DeviceEntranceInfoPO> list = iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceStatus.getDeviceName());
            if (list.size() == 0) {
                list = iDeviceEntranceInfoDao.getDoorByGroup(deviceStatus.getDeviceName());
            }
            for (DeviceEntranceInfoPO po : list) {
//                String status = redisService.get(RedisConstant.DEVICE_ENTRANCE_IS_ONLINE_KEY+po.getDeviceUnique());
//                if(null == status || "0".equals(status)) {
//                    status = "OFFLINE";
//                }else {
//                    status = "ONLINE";
//                }
                if(!oldStatus.equals(IOTStatus)) {
                    //保存上下线日志
                    DeviceOnlineStatusAlterLogPO deviceOnlineStatusAlterLogPO = new DeviceOnlineStatusAlterLogPO();
                    if("ONLINE".equals(IOTStatus)){
                        deviceOnlineStatusAlterLogPO.setOnlineStatus(1);
                    }else {
                        deviceOnlineStatusAlterLogPO.setOnlineStatus(0);
                    }
                    deviceOnlineStatusAlterLogPO.setDeviceType(2);
                    deviceOnlineStatusAlterLogPO.setDeviceUnique(po.getDeviceUnique());
                    deviceOnlineStatusAlterLogPO.setCreateTime(nowTime);
                    deviceOnlineStatusAlterLogPO.setStatusAlterTime(nowTime);
                    deviceOnlineStatusAlterLogPO.setStatus(1);
                    saveOnlineStatusAlterLog(deviceOnlineStatusAlterLogPO);

                }
            }
        }
        if ("4".equals(type)) {//群控器
//            String status = redisService.get(RedisConstant.DEVICE_CLUSTER_IS_ONLINE_KEY+deviceStatus.getDeviceName());
//            if(null == status || "0".equals(status)) {
//                status = "OFFLINE";
//            }else {
//                status = "ONLINE";
//            }
            if(!oldStatus.equals(IOTStatus)) {
                //保存上下线日志
                DeviceOnlineStatusAlterLogPO deviceOnlineStatusAlterLogPO = new DeviceOnlineStatusAlterLogPO();
                if("ONLINE".equals(IOTStatus)){
                    deviceOnlineStatusAlterLogPO.setOnlineStatus(1);
                }else {
                    deviceOnlineStatusAlterLogPO.setOnlineStatus(0);
                }
                deviceOnlineStatusAlterLogPO.setDeviceType(3);
                deviceOnlineStatusAlterLogPO.setDeviceUnique(deviceStatus.getDeviceName());
                deviceOnlineStatusAlterLogPO.setCreateTime(nowTime);
                deviceOnlineStatusAlterLogPO.setStatusAlterTime(nowTime);
                deviceOnlineStatusAlterLogPO.setStatus(1);
                saveOnlineStatusAlterLog(deviceOnlineStatusAlterLogPO);

            }
        }
        if ("5".equals(type) ) {//联动器
            List<DeviceEntranceInfoPO> list = iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceStatus.getDeviceName());
            if (list.size() == 0) {
                list = iDeviceEntranceInfoDao.getDoorByGroup(deviceStatus.getDeviceName());
            }
            for (DeviceEntranceInfoPO po : list) {
//                String status = redisService.get(RedisConstant.DEVICE_WIPPEN_IS_ONLINE_KEY+po.getDeviceUnique());
//                if(null == status || "0".equals(status)) {
//                    status = "OFFLINE";
//                }else {
//                    status = "ONLINE";
//                }
                if(!oldStatus.equals(IOTStatus)) {
                    //保存上下线日志
                    DeviceOnlineStatusAlterLogPO deviceOnlineStatusAlterLogPO = new DeviceOnlineStatusAlterLogPO();
                    if("ONLINE".equals(IOTStatus)){
                        deviceOnlineStatusAlterLogPO.setOnlineStatus(1);
                    }else {
                        deviceOnlineStatusAlterLogPO.setOnlineStatus(0);
                    }
                    deviceOnlineStatusAlterLogPO.setDeviceType(4);
                    deviceOnlineStatusAlterLogPO.setDeviceUnique(po.getDeviceUnique());
                    deviceOnlineStatusAlterLogPO.setCreateTime(nowTime);
                    deviceOnlineStatusAlterLogPO.setStatusAlterTime(nowTime);
                    deviceOnlineStatusAlterLogPO.setStatus(1);
                    saveOnlineStatusAlterLog(deviceOnlineStatusAlterLogPO);

                }
            }
        }
        if ("6".equals(type)) {//平板
//            String status = redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY+deviceStatus.getDeviceName());
//            if(null == status || "0".equals(status)) {
//                status = "OFFLINE";
//            }else {
//                status = "ONLINE";
//            }
            if(!oldStatus.equals(IOTStatus)) {
                //保存上下线日志
                DeviceOnlineStatusAlterLogPO deviceOnlineStatusAlterLogPO = new DeviceOnlineStatusAlterLogPO();
                if("ONLINE".equals(IOTStatus)){
                    deviceOnlineStatusAlterLogPO.setOnlineStatus(1);
                }else {
                    deviceOnlineStatusAlterLogPO.setOnlineStatus(0);
                }
                deviceOnlineStatusAlterLogPO.setDeviceType(5);
                deviceOnlineStatusAlterLogPO.setDeviceUnique(deviceStatus.getDeviceName());
                deviceOnlineStatusAlterLogPO.setCreateTime(nowTime);
                deviceOnlineStatusAlterLogPO.setStatusAlterTime(nowTime);
                deviceOnlineStatusAlterLogPO.setStatus(1);
                saveOnlineStatusAlterLog(deviceOnlineStatusAlterLogPO);

            }
        }
        if ("8".equals(type)) {//一体式人脸识别门禁
            List<DeviceEntranceInfoPO> list = iDeviceEntranceInfoDao.getAllDoorByDeviceUnique(deviceStatus.getDeviceName());
            if (list.size() == 0) {
                list = iDeviceEntranceInfoDao.getDoorByGroup(deviceStatus.getDeviceName());
            }
            for (DeviceEntranceInfoPO po : list) {
//                String status = redisService.get(RedisConstant.DEVICE_UNIBODY_FACE_IS_ONLINE_KEY+po.getDeviceUnique());
//                if(null == status || "0".equals(status)) {
//                    status = "OFFLINE";
//                }else {
//                    status = "ONLINE";
//                }
                if(!oldStatus.equals(IOTStatus)) {
                    //保存上下线日志
                    DeviceOnlineStatusAlterLogPO deviceOnlineStatusAlterLogPO = new DeviceOnlineStatusAlterLogPO();
                    if("ONLINE".equals(IOTStatus)){
                        deviceOnlineStatusAlterLogPO.setOnlineStatus(1);
                    }else {
                        deviceOnlineStatusAlterLogPO.setOnlineStatus(0);
                    }
                    deviceOnlineStatusAlterLogPO.setDeviceType(6);
                    deviceOnlineStatusAlterLogPO.setDeviceUnique(po.getDeviceUnique());
                    deviceOnlineStatusAlterLogPO.setCreateTime(nowTime);
                    deviceOnlineStatusAlterLogPO.setStatusAlterTime(nowTime);
                    deviceOnlineStatusAlterLogPO.setStatus(1);
                    saveOnlineStatusAlterLog(deviceOnlineStatusAlterLogPO);

                }
            }
        }
    }
    /**
     * <desc>
     *      保存设备在线日志
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/24 18:16
     */
    private void saveOnlineStatusAlterLog(DeviceOnlineStatusAlterLogPO deviceOnlineStatusAlterLogPO){
        Date nowTime = new Date();

        deviceOnlineStatusAlterLogPO.setStatus(1);
        deviceOnlineStatusAlterLogPO.setCreateTime(nowTime);
        deviceOnlineStatusAlterLogPO.setStatusAlterTime(nowTime);
        try {
            Map<String, Object> params = SqlUtil.durableData(deviceOnlineStatusAlterLogPO, PlatformConstants.TABLE_SAVE);
            iotInteriorDao.save(params);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
    }
    /**
     * <desc>
     *     删除设备属性
     * </desc>
     *
     * @param productKey
     * @param deviceUnique
     * @param deviceProKeyJs
     * @author Jiaqi.X
     * @createDate 2018/03/17
     */
    public boolean deleteDeviceProp(String productKey, String deviceUnique,JSONObject deviceProKeyJs){
        DeleteDevicePropRequest request = new DeleteDevicePropRequest();
        request.setProductKey(productKey);
        request.setDeviceName(deviceUnique);
        Set<String> deviceProSet = deviceProKeyJs.keySet();
        for (String prokey:deviceProSet){
            request.setPropKey(prokey);
            DeleteDevicePropResponse response = (DeleteDevicePropResponse) executeTest(request);
            if (response == null){
                LOG.info("创建产品失败！无法获取CreateProductResponse对象");
                return false;
            }
            if (response != null && response.getSuccess() != false) {
                LOG.info("删除设备属性成功！");

            } else {
                LOG.info("删除设备属性失败！requestId:" + response.getRequestId() + "原因：" + response.getErrorMessage());
                return  false;
            }
        }
        return  true;
    }

    /**
     * <desc>
     *      发布消息
     * </desc>
     *
     * @param productKey  产品key
     * @param topic  设备topic地址
     * @param msg 消息内容
     * @author Jiaqi.X
     * @createDate 2018/04/11
     */
    @Override
    public void pubDeviceMessage(String productKey, String topic, String msg) {
            LOG.info("【把指令转给iot】{}", msg);
            PubRequest request = new PubRequest();
            request.setProductKey(productKey);
            request.setTopicFullName("/" + productKey + topic);
            request.setMessageContent(Base64.encodeBase64String(msg.getBytes()));
            request.setQos(1);
            PubResponse response = (PubResponse) executeTest(request);
            if (response != null && response.getSuccess() != false) {
                LOG.info("发送云设备控制消息成功！messageId：" + response.getMessageId()+topic+msg);
            } else {
                if(response != null) {
                    LOG.info("发送云设备控制消息失败！requestId:" + response.getRequestId() + "原因：" + response.getErrorMessage());
                }
            }
    }


}
